package com.woniuxy.mail.rabbit_demo.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.util.LogUtils;
import com.study.util.ResponseResult;
import com.study.vo.CourseInfoVO;
import com.woniuxy.mail.rabbit_demo.entity.Order;
import com.woniuxy.mail.rabbit_demo.service.CourseService;
import com.woniuxy.mail.rabbit_demo.service.EmailService;
import com.woniuxy.mail.rabbit_demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;

/**
 * @author fengbenpeng
 * @description: 监听死信队列,订单支付未成功
 * @date 2022/3/14 19:33
 */
@Slf4j
@Component
public class ConcelListener {
    @Autowired
    private EmailService emailService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CourseService courseService;
    /**
     * 监听某个队列的消息
     * @param message 接收到的消息
     */
    @RabbitListener(queues = "dead_queue")//这里表示的是监听order_add_email_queue这个队列的消息
    public void myListener1(String message){//订单对象字符串
        LogUtils.info(log,"dead_queue",message);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Order order = objectMapper.readValue(message, Order.class);
            Context context = new Context();
            context.setVariable("order",order);
//            ResponseResult responseResult = orderService.payOrder(order.getId());
//            if(responseResult.getCode()!=200) {
                //死信队列收到消息以后,通过openfen调用删除订单
             ResponseResult<Order> orderById = orderService.findOrderById(order.getId());
            Order data = orderById.getData();
            if(data.getStatus()!=1){
            orderService.deleteOrderById(order.getId());
                //获取课程对象
                ResponseResult<CourseInfoVO> result = courseService.getById(order.getCourseId());
                //更新购买的数量
                final CourseInfoVO courseInfoVO = result.getData();
                Long buyCount = courseInfoVO.getBuyCount();
                courseInfoVO.setBuyCount(buyCount - 1);
                //更新课程对象
                courseService.updateById(courseInfoVO);
            }
            //sender表示的是发送者,accepter表示的是接收者
            emailService.sendEmail("订单超时未支付",context,
                    "1558788078@qq.com","1558788078@qq.com","email_cancle.html");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
